<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="归属店员" prop="clerkId">
        <el-select
          v-model="queryParams.clerkId"
          clearable
          placeholder="请选择店员"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in clerkList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式" prop="tel">
        <el-input
          v-model="queryParams.tel"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:customer:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:customer:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:customer:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:customer:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="customerList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <!-- <el-table-column label="商铺ID" align="center" prop="shopId" /> -->
      <el-table-column label="名字" align="center" prop="name" />
      <el-table-column label="联系方式" align="center" prop="tel" />
      <el-table-column label="会员积分" align="center" prop="tel" />
      <el-table-column label="生日" align="center" prop="birthday" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="归属店员" align="center" prop="clerkId">
        <template slot-scope="scope">
          <div
            v-for="item in allClerkList"
            :key="item.id"
            v-show="item.id === scope.row.clerkId"
          >
            <el-tag> {{ item.name }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="排序字段" align="center" prop="sort" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="350"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:customer:edit']"
            >顾客信息</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="topUp(scope.row)"
            v-hasPermi="['product:customer:edit']"
            >充值</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="expense(scope.row)"
            v-hasPermi="['product:customer:edit']"
            >消费记录</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="userClerk(scope.row)"
            v-hasPermi="['product:customer:edit']"
            >分配店员</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:customer:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.rowsPerPage"
      @pagination="getList"
    />

    <!-- 添加或修改顾客对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="商铺ID" prop="shopId">
          <el-input v-model="form.shopId" placeholder="请输入商铺ID" />
        </el-form-item> -->
        <el-form-item label="名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入名字" />
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            value-format="yyyy.MM.dd"
            placeholder="请选择生日"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number
            v-model="form.age"
            :min="1"
            :max="100"
            label="年龄"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
        <!-- <el-form-item label="排序字段" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序字段" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配 -->
    <el-dialog title="分配店员" :visible.sync="dialogVisible" width="30%">
      <el-form>
        <el-form-item label="分配店员" prop="clerkId">
          <el-select v-model="userClerkId" clearable placeholder="请选择店员">
            <el-option
              v-for="item in clerkList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelClerk">取 消</el-button>
        <el-button type="primary" @click="closeClerk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 消费记录 -->
    <el-dialog title="消费情况" :visible.sync="expenseVisible" width="500px">
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-statistic
              group-separator=","
              :precision="2"
              decimal-separator="."
              :value="countCost"
              title="总消费金额"
            >
              <template slot="prefix">
                <i class="el-icon-s-flag" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-s-flag" style="color: blue"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic :value="number" title="消费次数">
              <template slot="suffix">
                <span @click="like = !like" class="like">
                  <i class="el-icon-star-on" style="color: red"></i>
                </span>
              </template>
            </el-statistic>
          </div>
        </el-col>
      </el-row>
      <el-dialog
        width="30%"
        title="消费历史"
        :visible.sync="innerVisible"
        append-to-body
        class="scrollbar"
      >
        <el-scrollbar style="height: 100%">
          <el-timeline v-for="item in customerOrder" :key="item.id">
            <el-timeline-item
              :timestamp="parseTime(item.appointTime, '{y}/{m}/{d}')"
              placement="top"
            >
              <el-card>
                <h4>项目： {{ item.projectName }}</h4>
                <h4>金额： {{ item.needPay }}元</h4>
                <p style="color: #909399">
                  {{ item.customer }} 消费于 {{ item.appointTime }}
                </p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-scrollbar>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">关 闭</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="innerVisible = true"
          >消费明细</el-button
        >
        <el-button @click="expenseVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 积分充值 -->
    <el-dialog title="会员充值" :visible.sync="topUpVisible" width="30%">
      <div>
        <el-input v-model="money" autocomplete="off"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel2">取 消</el-button>
        <el-button type="primary" @click="chongzhi">充 值</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustomer,
  getCustomer,
  delCustomer,
  addCustomer,
  updateCustomer,
  bindClerk,
  delCustomers,
  getDic,
} from "@/api/product/customer";
import { listOrder } from "@/api/product/order";
import { listClerk } from "@/api/product/clerk";
import data from "../../system/dict/data.vue";
export default {
  components: { data },
  name: "Customer",
  data() {
    return {
      // 充值金额
      money: "",
      options: [
        {
          value: "男",
          label: "男",
        },
        {
          value: "女",
          label: "女",
        },
      ],
      //店员id
      userClerkId: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 顾客表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogVisible: false,
      expenseVisible: false,
      innerVisible: false,
      topUpVisible: false,
      // 查询参数
      queryParams: {
        page: 1,
        rowsPerPage: 10,
        shopId: null,
        clerkId: null,
        name: null,
        tel: null,
        birthday: null,
        sex: null,
        age: null,
        createBy: null,
        createTime: null,
        sort: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //店员dic
      clerkList: [],
      allClerkList: [],
      // 消费订单
      customerOrder: [],

      //消费次数
      number: 0,
      TopUpform: {},
    };
  },
  created() {
    this.getList();
    this.getclerkDic();
    this.getclerkList();
  },
  computed: {
    //属性名字（计算属性名称）
    //属性的值（计算属性处理函数）
    countCost() {
      // 对依赖的数据进行处理，且进行return
      return this.customerOrder.reduce(
        (pre, current) => pre + parseFloat(current.price),
        0
      );
    },
  },
  methods: {
    // 积分充值
    topUp(row) {
      getCustomer(row.id).then((response) => {
        this.TopUpform = response.data;
        this.topUpVisible = true;
      });
    },
    chongzhi() {
      this.TopUpform.remark =
        parseInt(this.money) +
        (parseInt(this.TopUpform.remark) ? parseInt(this.TopUpform.remark) : 0);
      updateCustomer(this.TopUpform).then((response) => {
        this.$modal.msgSuccess("充值成功");
        this.open = false;
        this.getList();
      });
      this.topUpVisible = false;
      this.reset2();
      this.money = "";
    },
    // 消费记录
    expense(row) {
      listOrder().then((res) => {
        this.customerOrder = res.data.list.filter(
          (item) => item.customer == row.name
        );
        this.expenseVisible = true;
        this.number = this.customerOrder.length;
      });
    },
    // 获取店员列表
    getclerkList() {
      listClerk().then((res) => {
        this.allClerkList = res.data.list;
      });
    },

    /** 查询顾客列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then((response) => {
        this.customerList = response.data.list;
        this.total = response.data.totalCount;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel2() {
      this.topUpVisible = false;
      this.reset2();
    },

    // 绑定店员
    closeClerk() {
      bindClerk(this.userClerkId, this.userId).then((res) => {
        if (res.code === 200) {
          this.$modal.msgSuccess("绑定成功");
          this.getList();
          this.userClerkId = "";
          this.userId = "";
        }
      });
      this.dialogVisible = false;
    },
    //店员绑定取消
    cancelClerk() {
      this.userClerkId = "";
      this.userId = "";
      this.dialogVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopId: null,
        clerkId: null,
        name: null,
        tel: null,
        birthday: null,
        sex: null,
        age: null,
        remark: null,
        createBy: null,
        createTime: null,
        sort: null,
      };
      this.resetForm("form");
    },
    reset2() {
      this.TopUpform = {
        id: null,
        shopId: null,
        clerkId: null,
        name: null,
        tel: null,
        birthday: null,
        sex: null,
        age: null,
        remark: null,
        createBy: null,
        createTime: null,
        sort: null,
      };
      this.resetForm("TopUpform");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // this.getclerkDic();
      this.title = "添加顾客";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const id = row.id || this.ids;
      getCustomer(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改顾客";
      });
    },
    //分配店员
    userClerk(row) {
      this.userId = row.id;
      if (row.clerkId) {
        this.userClerkId = row.clerkId;
      }
      this.getclerkDic();
      this.dialogVisible = true;
    },
    //店员字典
    getclerkDic() {
      getDic().then((res) => {
        this.clerkList = res.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除顾客编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCustomer(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/customer/export",
        {
          ...this.queryParams,
        },
        `customer_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
